
/*
 * FeedExpress
 * (C) Copyright 2003 Jeppe Cramon (jeppe@cramon.dk)
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 * Disclaimer:
 * -----------
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied. The entire risk as to the
 * quality and performance of the software is with you. Should the
 * software prove defective, you assume the cost of all necessary
 * servicing, repair, or correction. In no event shall the author,
 * copyright holder, or any other party who may redistribute the
 * software be liable to you for damages, including any general,
 * special, incidental, or consequential damages arising out of
 * the use or inability to use the software (including, but not
 * limited to, loss of data, data being rendered inaccurate, loss of
 * business profits, loss of business information, business
 * interruptions, loss sustained by you or third parties, or a
 * failure of the software to operate with any other software) even
 * if the author, copyright holder, or other party has been advised
 * of the possibility of such damages. 
 * 
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Pbdms.BusinessLogic.Mail
{
    public class InboxManager
    {
        //refresh handlers
        public event EventHandler RefreshStart;
        public event EventHandler RefreshDone;
        public event EventHandler NewMessages;

        private MailBox mailBox;
        private Common.Interfaces.ICache mCache;
        private bool IsRefreshing = false;
        private bool hasInitializedMailboxReferences = false;
        
        public InboxManager()
        {

            this.mCache = CacheFactory.getInstance().getCacheHandler();
        }
        public InboxManager(MailBox mailbox)
        {
            this.mailBox = mailbox;
            this.mCache = CacheFactory.getInstance().getCacheHandler();
        }
        public IDictionary messages
        {
            get
            {
                IDictionary returnValue = (IDictionary)mCache.getAll(mailBox);
                if (!hasInitializedMailboxReferences && returnValue != null)
                {
                    foreach (Message message in returnValue.Values)
                    {
                        message.mailBox = mailBox;
                    }
                    hasInitializedMailboxReferences = true;
                }
                return returnValue; ;
            }
        }
        public int getUnreadCount()
        {
            IDictionary messages= (IDictionary)mCache.getAll(mailBox);
            int count = 0;
            if (messages == null)
            {
                return count;
            }

            foreach (Message message in messages.Values)
            {
                if (!message.isRead)
                {
                    count++;
                }
            }
            return count;
        }
        /// <summary>
        /// Saves the entire message cache to disk. 
        /// </summary>
        public void saveCompleteMessageCache()
        {
            mCache.saveCache();
        }
        /// <summary>
        /// Marks all feeds as read
        /// </summary>
        public void markAllAsRead()
        {
            IDictionary messages = (IDictionary)mCache.getAll(mailBox);
            foreach (Message message in messages.Values)
            {
                message.isRead = true;
            }
        }
        
        /// <summary>
        /// Marks all feeds as unread
        /// </summary>
        public void markAllAsUnRead()
        {
            IDictionary messages = (IDictionary)mCache.getAll(mailBox);
            foreach (Message message in messages.Values)
            {
                message.isRead = false;
            }
        }

        //delete all messages from the cache
        public void deleteMessages()
        {
            mCache.clear(mailBox);
        }
        public void deleteAMessage(MailBox mailBox, Message message)
        {
            mCache.remove(mailBox, message);
            try
            {
                OpenDHTLib.OpenLookUp openDHT = new Pbdms.OpenDHTLib.OpenLookUp();
                openDHT.Rm(mailBox.KeyControl.readSecretKey().KeyId.ToString("X") + "'s Inbox", message.key + " Size:" + message.size.ToString(), message.secret, 604800);
            }
            catch
            {

            }
           
        }

        

        public void RefreshInbox()
        {

            lock (this)
            {
                if (IsRefreshing)
                {
                    return;
                }
                else
                {
                    IsRefreshing = true;
                }
            }

            ThreadStart thsCheckInbox = new ThreadStart(RefreshingInbox);
            Thread thCheckInbox = new Thread(thsCheckInbox);
            thCheckInbox.Start();


        }
        public void saveCompleteCache()
        {
            mCache.saveCache();
        }
        private void RefreshingInbox()
        {
            OpenDHTLib.OpenLookUp openDHT = new Pbdms.OpenDHTLib.OpenLookUp();

            if (RefreshStart != null)
            {
                RefreshStart(mailBox, EventArgs.Empty);
            }
           
               
                string InboxKey = mailBox.KeyControl.readSecretKey().KeyId.ToString("X") + "'s Inbox";
                //retreieve all inbox invoices
                string[] values = openDHT.GetStringValues(InboxKey);
                if (values != null)
                {
                    Boolean finished = false;
                    Hashtable newMessages = new Hashtable();
                    for (int i = 0; i < values.Length; i++)
                    {
                        MessageDownloader offlineMsgDownloader = new MessageDownloader(values[i], mailBox.KeyControl, mailBox.pubKeyControl);
                        offlineMsgDownloader.DownloadMessage();
                        finished = offlineMsgDownloader.DownloadFinished;
                        if (finished == true)
                        {
                            Message message = offlineMsgDownloader.Message;
                            newMessages.Add(message.key, message);                            
                        }
                    }
                    foreach (Message messageEntry in newMessages.Values)
                    {
                        messageEntry.mailBox = mailBox;
                    }
                    Boolean updated = mCache.updateAll(mailBox, newMessages);
                    if (updated == true)
                    {
                        if (NewMessages != null)
                        {
                            NewMessages(mailBox, EventArgs.Empty);
                        }
                    }
                    
                }
                
                if (RefreshDone != null)
                {
                    RefreshDone(mailBox, EventArgs.Empty);
                }
            IsRefreshing = false;
        }
    }
}
